package com.forum.controller.filter;

import com.alibaba.fastjson.JSON;
import com.common.entity.ApiResult;
import com.common.utils.LocalContext;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.HttpStatus;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @author Tsing
 * 登录验证拦截器 通过对Token的校验实现登录状态的验证
 */
@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Slf4j
@Order(1)
public class CheckLoginFilter implements Filter {
    @Value("${redis-config.token-prefix}")
    private String tokenPrefix;

    private final RedisTemplate<String,String> redisTemplate;

    //需要验证登录的请求路径
    private String[] checkUris=new String[]{
            "/api/confessions/upload",
            "/api/confessions/current",
            "/api/confessions/comment/send",
            "/api/photowalls/submitImages",
            "/api/confessions/comment/send",
            "/api/confessions/reply/send",
            "/api/photowalls/getPhotoDetail",
            "/api/photowalls/likePhoto",
            "/api/photowalls/getMyPhotoWalls",
            "/api/talks/create",
            "/api/talks/posts/create",
            "/api/talks/currentUser",
            "/api/talks/posts/comment/send",
            "/api/talks/posts/comment/reply",
            "/api/forum_users/info/edit",
            "/api/forum_users/password/update",
            "/api/forum_users/info"

    };

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String requestPath = request.getRequestURI();
        ServletOutputStream outputStream = response.getOutputStream();
        ValueOperations<String,String> valueOperations = redisTemplate.opsForValue();
        String authentication = request.getHeader("Authorization");
        String userId = valueOperations.get(tokenPrefix+authentication);

        if(!checkUri(requestPath)){
            //判断token是否为空 非空则判断是否在redis中有存储
            if(!Objects.isNull(authentication)&&!Objects.isNull(userId)){
                LocalContext.remove();
                LocalContext.setCurrentUserId(Integer.parseInt(userId));
                filterChain.doFilter(servletRequest,servletResponse);
            }else{
                outputStream.write(JSON.toJSONString(ApiResult.fail(HttpStatus.UNAUTHORIZED.value(),"用户未登录")).getBytes());
                return;
            }
        }else{
            filterChain.doFilter(servletRequest,servletResponse);
        }


    }

    private Boolean checkUri(String currentUri){
        for (int i = 0; i < checkUris.length; i++) {
            if(checkUris[i].equals(currentUri)){
                return false;
            }
        }
        return true;
    }
}
